<template>
  <div class="personalSetting_container pr-1 pl-1">
		<div class="personalSetting_container_userInfo">
			<img class="user_img mb-1" :src="userInfo.image" @error="handleImageError" @click="changeUserImg" alt="">
			<div class="user_info">
				<span class="user_info_name mr-1">{{userInfo.name}}</span>
				<img src="@/image/personalCenter/setting/icon_bianji@1x.png" @click="changeName(userInfo.name,'name')" alt="">
			</div>
		</div>
		<div class="personalSetting_container_settingList">
			<div class="personalSetting_container_settingList_item pt-0 pb-0 pl-1 pr-1 br-16 mb-0" v-for="(item,index) in list" :key="index" @click="settingClick(item)">
				<img class="setting_img" :src="item.image" alt="">
				<div class="item_content">
					<div class="item_content_left">
						<div class="item_content_left_title">{{item.title}}</div>
						<div class="item_content_left_label" v-if="!!item.label">{{item.label}}</div>
					</div>
					<img class="item_content_icon" :src="item.icon" alt=""/>
				</div>
			</div>
		</div>
		<van-popup v-model="popupShow" position="bottom" :style="{ height: 'auto' }" >
				<div class="sex_box" @click="changeSex(1)">{{ $t("男") }}</div>
				<div @click="changeSex(2)">{{ $t("女") }}</div>
				<div class="btns" @click="popupShow = false">{{ $t("取消") }}</div>
		</van-popup>
		<van-popup v-model="changeUserImgShow" position="bottom" :style="{ height: 'auto' }" >
			<div class="sex_box" @click="changeUserImgs(1)">{{ $t("更换头像") }}</div>
			<div @click="changeUserImgs(2)">{{ $t("查看头像") }}</div>
			<div class="btns" @click="changeUserImgShow = false">{{ $t("取消") }}</div>
		</van-popup>
		<van-image-preview v-model="detaileShow" :images="[userInfo.image]" closeable :showIndex="false">
		</van-image-preview>
		<div v-if="detaileShow" class="btn_download" @click="downloadImage">{{ $t('点击下载') }}</div>
	</div>
</template>

<script>
import { clipboard } from '@/utils';
import { uploadFile , updateUserInfo , getUserInfo } from "@/request/personalCenter"
export default {
	name: "PersonalSetting",
	data(){
		return {
			userInfo:{},
			defaultImage: require("@/image/personalCenter/head.png"),
			list:[],
			popupShow:false,
			changeUserImgShow: false,
			detaileShow: false
		}
	},
	mounted(){
		this.getUserInfo()
		this.disposeList()
	},
	methods:{
		getUserInfo(){
			if(this.$route.params.value && this.$route.params.type){
				this.userInfo[this.$route.params.type] = this.$route.params.value
				this.disposeList()
			}
			getUserInfo().then(res=>{
			    if(res.code == 1){
					let data = res.data
					// 请求用户数据
					this.userInfo = {
						id: data.id,
						name: data.nickname,
						image:  data.avatar || require("@/image/personalCenter/head.png"),
						level: data.level.name,
						UID: data.code,
						email: data.username,
						sex: data.gender,
						sign: data.bio,
						is_autonym: this.disposeAutonym(data)
					}
					this.disposeList()
				}else{
					this.$toast.fail(res.msg)
				}
			})
			
		},
		disposeAutonym(item){
			if(item.is_shiming == 2 && item.is_life == 2 && item.is_tax == 2 && item.phone){
				return true
			}else{
				return false
			}
		},
		setUserInfo(obj){
			//{ nickname 昵称, avatar 头像, gender 性别 1男2女, bio 个性签名 }
			updateUserInfo(obj).then(res=>{
				if(res.code == 1){
					// 更改成功
					this.$toast.success(this.$t("更改成功"))
					console.log(res.data)
					if(obj.avatar){
						this.userInfo.image = obj.avatar
					}else if(obj.gender){
						this.userInfo.sex = obj.gender
					}
					this.disposeList()
				}else{
					this.$toast.fail(res.msg)
				}
			})
		},
		handleImageError(event){
			event.target.src = this.defaultImage;
			event.target.onerror = null; // 防止备用图也出错时循环报错
		},
		disposeList(){
			this.list = [
				{
					image: require("@/image/personalCenter/setting/user_icon1.png"),
					title: this.$t('用户等级'),
					icon: require("@/image/aiQuantization/indexTop/arrow.png"),
					label: !!this.userInfo.level || this.userInfo.level == 0 ? this.userInfo.level : ''
				},
				{
					image: require("@/image/personalCenter/setting/user_icon2.png"),
					title: this.$t('UID'),
					icon: require("@/image/homePage/aiImageDetail/cope.png"),
					label: this.userInfo.UID ? this.userInfo.UID : ''
				},
				{
					image: require("@/image/personalCenter/setting/user_icon9.png"),
					title: this.$t('绑定邮箱'),
					icon: require("@/image/homePage/aiImageDetail/cope.png"),
					label: this.userInfo.email ? this.userInfo.email : ''
				},
				{
					image: require("@/image/personalCenter/setting/user_icon4.png"),
					title: this.$t('性别'),
					icon: require("@/image/aiQuantization/indexTop/arrow.png"),
					label: this.userInfo.sex == 1 ? this.$t('男') : this.$t('女')
				},
				{
					image: require("@/image/personalCenter/setting/user_icon5.png"),
					title: this.$t('个性签名'),
					icon: require("@/image/aiQuantization/indexTop/arrow.png"),
					label: this.userInfo.sign ? this.userInfo.sign : ''
				},
				{
					image: require("@/image/personalCenter/setting/user_icon8.png"),
					title: this.$t('实名认证'),
					icon: require("@/image/aiQuantization/indexTop/arrow.png"),
					label: this.userInfo.is_autonym ? this.$t("已认证") : this.$t("未认证")
				},
			]
		},
		settingClick(item){
			switch(item.title){
				case this.$t('用户等级'):
					this.$router.push({name: 'PersonalSettingLevel'})
					break
				case this.$t('UID'):
					// 复制UID
					this.copyText(this.userInfo.UID)
					break
				case this.$t('绑定邮箱'):
					// 复制邮箱
					this.copyText(this.userInfo.email)
					break
				case this.$t('性别'):
					// 弹窗更改
					this.popupShow = true
					break
				case this.$t('个性签名'):
					this.changeName(this.userInfo.sign,'sign')
					break
				case this.$t('实名认证'):
					// 是否携带user id
					this.$router.push({name: 'PersonalSettingRealName',params:{id:this.userInfo.id}})
					break
				default:
					break
			}
		},
		async copyText(value) {
			try {
				await clipboard.copy(value);
				this.$toast.success(this.$t('复制成功'));
			} catch {
				this.$toast.fail(this.$t('复制失败'));
			}
		},
		changeName(val,type){
			// 跳转更改用户名界面
			console.log(val)
			if(this.$route.name != 'PersonalSettingCompile'){
				this.$router.push({
					name: 'PersonalSettingCompile',
					params:{
						value: val,
						type: type
					}
				});
      }
		},
		changeSex(sex){
			// 修改性别
			this.setUserInfo({gender:sex})
			this.popupShow = false
		},
		changeUserImg(){
			this.changeUserImgShow = true
		},
		changeUserImgs(type){
			
			if(type == 1){
				// 更换头像
				const input = document.createElement('input')
				input.type = 'file'
				input.accept = 'image/*'
				input.onchange = (e) => {
					const file = e.target.files[0]
					if (file) {
						this.uploadImage(file)
					}
				}
				input.click()
			}else{
				this.detaileShow = true
			}
		},
		async uploadImage(file) {
			try {
				// 创建FormData对象
				const formData = new FormData()
				formData.append('file', file)
				formData.append('type', 'avatar')
				
				// 调用上传接口
				const res = await uploadFile(formData)
				if (res.code === 1) {
					console.log(res.data)
					
					this.$toast.success(this.$t("头像上传成功"))
					this.setUserInfo({avatar:res.data})
					
				} else {
					this.$toast.fail(res.msg || this.$t("上传失败"))
				}
			} catch (error) {
				this.$toast.fail(this.$t("上传出错"))
				console.error(error)
			} finally {
				this.changeUserImgShow = false
			}
		},
		downloadImage() {
			if(this.userInfo.image) {
				const xhr = new XMLHttpRequest();
				xhr.open('GET', this.userInfo.image, true);
				xhr.responseType = 'blob';
				
				xhr.onload = () => {
					if (xhr.status === 200) {
						const blob = new Blob([xhr.response], {type: 'image/png'});
						const url = window.URL.createObjectURL(blob);
						const link = document.createElement('a');
						link.href = url;
						link.download = new Date().getTime() + '.png';
						link.style.display = 'none';
						document.body.appendChild(link);
						link.click();
						window.URL.revokeObjectURL(url);
						document.body.removeChild(link);
					}
				};
					
				xhr.send();
			} else {
				this.$toast(this.$t('暂无图片可下载'));
			}
		}
	}
}
</script>

<style>

</style>